package com.example.actionhandlers.actions;

import org.json.JSONException;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;

import com.example.actionhandlers.AbstractAction;
import com.example.singletones.contextObj;

public class ChangeSyncOfAccount extends AbstractAction {

	public boolean isApplicable(JSONObject jsonObj) {
		try {
			return jsonObj.has("actionName")
					&& jsonObj.getString("actionName").equalsIgnoreCase(
							"change_account_sync");
		} catch (JSONException e) {
			return false;
		}
	}

	public void performAction(JSONObject jsonObj) throws Exception {
		Account[] accounts = AccountManager.get(
				contextObj.getInstance().getmContext()).getAccounts();
		String type = jsonObj.getString("accountType");
		String name = jsonObj.getString("accountName");
		String authority = jsonObj.getString("authority");
		boolean syncActivity = jsonObj.getString("syncActivity").equals("1");
		Account searchedAccount = null;
		for (Account i : accounts) {
			if (i.name.equalsIgnoreCase(name) && i.type.equalsIgnoreCase(type)) {
				searchedAccount = i;
				break;
			}
		}
		if (searchedAccount != null) {
			ContentResolver.setSyncAutomatically(new Account(name, type),
					authority, syncActivity);
		}
	}

	public String getActionName() {
		return "change_account_sync";
	}
}
